﻿#include "VerifyDialog.h"
#include "ui_VerifyDialog.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QCryptographicHash>

VerifyDialog::VerifyDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::VerifyDialog),
    m_fpOk(false)
{
    ui->setupUi(this);
    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onUserIDChanged()));
    connect(ui->pushButtonCancel, SIGNAL(clicked(bool)),this, SLOT(onCancel()));
    connect(ui->pushButtonLogin, SIGNAL(clicked(bool)), this, SLOT(onLogin()));
    initUserInfo();

    connect(&m_reader, SIGNAL(onFingerprintReceived(QImage,QByteArray)) , this, SLOT(onFingerprintReceived(QImage,QByteArray)));
    m_reader.openDevice();
    m_reader.beginCapture();
}

void VerifyDialog::initUserInfo()
{
    QList <int> ids = m_dbLoader.userIDs();
    for(int i = 0; i< ids.size(); i++)
    {
        int fid = ids.at(i);
        ui->comboBox->addItem(QString::number(fid), fid);
    }
}

VerifyDialog::~VerifyDialog()
{
    if(m_reader.isRunning())
    {
        m_reader.cancelCapture();
        m_reader.wait(150);
    }
    m_reader.closeDevice();
    delete ui;
}

void VerifyDialog::onFingerprintRejected()
{

}
void VerifyDialog::onFingerprintReceived(QImage image, QByteArray fpTemplate)
{
    ui->labelImage->setPixmap(QPixmap::fromImage(image));
    int score = m_cacheDB.verifyFinger(m_regTemplate, fpTemplate);
    if(score > 50)
    {
        m_fpOk = true;
        ui->labelMessage->setText(QString::fromUtf8(u8"认证成功，点击 Log in 进入软件界面"));
    }
    else
    {
        ui->labelMessage->setText(QString::fromUtf8(u8"未通过认证，请重按手指！"));
        m_fpOk = false;
    }
}

void VerifyDialog::onCancel()
{
    done(QDialog::Rejected);
}

static QString md5(QString pwd)
{
    QCryptographicHash md5(QCryptographicHash::Md5);
    md5.addData(pwd.toLocal8Bit());
    QString ret(md5.result());
    return ret;
}

void VerifyDialog::onLogin()
{
    QString pw = ui->lineEditPassword->text();
    qDebug() << pw;
    qDebug() << m_password;
    if(m_password == md5(pw) || m_fpOk)
    {
        done(QDialog::Accepted);
    }
    else
    {
        ui->lineEditPassword->clear();
        QMessageBox msgBox;
        msgBox.setText(QString::fromUtf8(u8"密码错误，请重新输入密码！"));
        msgBox.exec();
    }
}

void VerifyDialog::onUserIDChanged()
{
    int fid = ui->comboBox->currentData().toInt();
    m_dbLoader.userInfo(fid, m_name, m_password, m_regTemplate);
    ui->labelName->setText(m_name);
    qDebug() << m_name;
}
